package com.hgx.lc.core.facade;

import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import com.hgx.su.common.pure.dto.*;
import com.hgx.su.common.pure.enums.DatabaseTypeEnum;
import com.hgx.lc.core.api.dto.DataTableReqDto;
import com.hgx.lc.core.api.dto.DataTableResDto;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库资源
 *
 * @author HGX
 * @since: 2020-12-01 15:03
 */
@RestController
@RequestMapping("/")
public class DataSourceController {

    /**
     * 获取数据库指定表结构
     *
     * @param paramRequest 请求参数
     * @return 返回数据
     */
    @PostMapping("getTable")
    public ResultResponse<List<DataTableResDto>> getTable(@RequestBody ParamRequest<DataTableReqDto> paramRequest) {

        DataSource ds2 = DSFactory.get(paramRequest.getBody().getDbCode());

        try {
            List<Entity> entity2 = SqlExecutor.query(ds2.getConnection(), "select DISTINCT COLUMN_NAME as columnName, COLUMN_COMMENT as columnComment,DATA_TYPE as dataType from information_schema.columns where table_schema= ? and table_name = ?", new EntityListHandler(), paramRequest.getBody().getTableSchema(), paramRequest.getBody().getTableName());

            List<DataTableResDto> list = new ArrayList<>();
            for (Entity e : entity2) {
                DataTableResDto resDto = new DataTableResDto();
                resDto.setColumnName(e.get("columnName").toString());
                resDto.setColumnComment(e.get("columnComment").toString());
                resDto.setDataType(e.get("dataType").toString());
                list.add(resDto);
            }

            ResultResponse<List<DataTableResDto>> res = new ResultResponse<>();
            res.setBody(list);
            return res;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return new ResultResponse<>();


    }

    /**
     * 获取所有的数据库类型
     *
     * @return 返回所有的数据库类型
     */
    @PostMapping("listAllDatabaseType")
    public ResultResponse<ListPackageDto<GeneralCodeNameDto>> listAllDatabaseType(@RequestBody ParamRequest<NullClassDto> paramRequest) {

        DatabaseTypeEnum[] values = DatabaseTypeEnum.values();

        List<GeneralCodeNameDto> list = new ArrayList<>();
        for (DatabaseTypeEnum typeEnum : values) {
            GeneralCodeNameDto codeNameDto = new GeneralCodeNameDto();
            codeNameDto.setCode(typeEnum.getCode());
            codeNameDto.setName(typeEnum.getName());
            list.add(codeNameDto);
        }

        return ResultResponse.ok(list);
    }


}
